#include "chart.h"
#include "ui_chart.h"
#include "widget.h"

bool Paint_now_past_Flag;

chart::chart(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::chart)
{
    ui->setupUi(this);

    back_set_color();
    timer_paint_now = new QTimer(this);
    connect(timer_paint_now, SIGNAL(timeout()), this, SLOT(Timer_task1_now_pain()));
    timer_paint_now->start(1000);                // 1秒钟触发一次

    ui->dateTime_start->setDisplayFormat("yyyy-MM-dd HH:mm:ss");
    ui->dateTime_end->setDisplayFormat("yyyy-MM-dd HH:mm:ss");
    QDateTime current_date_time =QDateTime::currentDateTime();
    ui->dateTime_start->setDateTime(current_date_time);
    ui->dateTime_end->setDateTime(current_date_time);
    InitChart();
}

void chart::InitChart()
{
    // 创建图表的各个部件
    QChart *chart = new QChart();

    // 将Chart添加到ChartView
    ui->graphicsView->setChart(chart);
    ui->graphicsView->setRenderHint(QPainter::Antialiasing);

    // 隐藏图例
    chart->legend()->hide();

    // 设置图表主题色
    ui->graphicsView->chart()->setTheme(QChart::ChartTheme(1));

    // 创建曲线序列
    QLineSeries *series0 = new QLineSeries();

    // 序列添加到图表
    chart->addSeries(series0);
    chart->setTheme(QChart::ChartThemeBlueCerulean);

    // 创建坐标轴
    QValueAxis *axisX = new QValueAxis;    // X轴
    axisX->setRange(0, 100);               // 设置坐标轴范围
    //axisX->setTitleText("时间");
   // axisX->setFormat("MM-dd"); // 显示为 月-日，例如：04-23
    axisX->setTitleText("时间");

    QValueAxis *axisY = new QValueAxis;    // Y轴
    axisY->setRange(0, 100);               // Y轴范围
    axisY->setMinorTickCount(4);           // s设置Y轴刻度

    // 添加坐标轴到图表
    chart->addAxis(axisX, Qt::AlignBottom);
    chart->addAxis(axisY, Qt::AlignLeft);

    // 附着序列到坐标轴
    series0->attachAxis(axisX);
    series0->attachAxis(axisY);
}


//实时采集数据1s画一次数据
void chart::Timer_task1_now_pain()
{
      if(Paint_now_past_Flag==1)
      {
          Paint_cansu_now();
      }
}
//实时采集运行函数
void chart::Paint_cansu_now()
{
    if (QSqlDatabase::contains("qt_sql_default_connection")) {
        QSqlDatabase::removeDatabase("qt_sql_default_connection");
    }

    // 添加新的数据库连接
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "qt_sql_default_connection");
    db.setDatabaseName("lyshark.db");
    if (!db.open()) {
        std::cout << db.lastError().text().toStdString() << std::endl;
        return;
    }

    // 执行查询获取最新的10000个数据
    QSqlQuery query(db);
    if(ui->comboBox_2->currentText()=="节点一"){
        if(ui->comboBox->currentText()=="温度"){
            query.prepare("SELECT datetime, temprature FROM Times1 ORDER BY id DESC LIMIT 10000");
        }
        else if(ui->comboBox->currentText()=="气体"){
            query.prepare("SELECT datetime, comgas FROM Times1 ORDER BY id DESC LIMIT 10000");
        }
        else if(ui->comboBox->currentText()=="火焰"){
            query.prepare("SELECT datetime, flame FROM Times1 ORDER BY id DESC LIMIT 10000");
        }
        else if(ui->comboBox->currentText()=="震动"){
            query.prepare("SELECT datetime, shake FROM Times1 ORDER BY id DESC LIMIT 10000");
        }
        else if(ui->comboBox->currentText()=="光照"){
            query.prepare("SELECT datetime, light FROM Times1 ORDER BY id DESC LIMIT 10000");
        }
    }
    else if(ui->comboBox_2->currentText()=="节点二"){
        if(ui->comboBox->currentText()=="温度"){
            query.prepare("SELECT datetime, temprature FROM Times2 ORDER BY id DESC LIMIT 10000");
        }
        else if(ui->comboBox->currentText()=="气体"){
            query.prepare("SELECT datetime, comgas FROM Times2 ORDER BY id DESC LIMIT 10000");
        }
        else if(ui->comboBox->currentText()=="火焰"){
            query.prepare("SELECT datetime, flame FROM Times2 ORDER BY id DESC LIMIT 10000");
        }
        else if(ui->comboBox->currentText()=="震动"){
            query.prepare("SELECT datetime, shake FROM Times2 ORDER BY id DESC LIMIT 10000");
        }
        else if(ui->comboBox->currentText()=="光照"){
            query.prepare("SELECT datetime, light FROM Times1 ORDER BY id DESC LIMIT 10000");
        }
    }
    else if(ui->comboBox_2->currentText()=="节点三"){
        if(ui->comboBox->currentText()=="温度"){
            query.prepare("SELECT datetime, temprature FROM Times3 ORDER BY id DESC LIMIT 10000");
        }
        else if(ui->comboBox->currentText()=="气体"){
            query.prepare("SELECT datetime, comgas FROM Times3 ORDER BY id DESC LIMIT 10000");
        }
        else if(ui->comboBox->currentText()=="火焰"){
            query.prepare("SELECT datetime, flame FROM Times3 ORDER BY id DESC LIMIT 10000");
        }
        else if(ui->comboBox->currentText()=="震动"){
            query.prepare("SELECT datetime, shake FROM Times3 ORDER BY id DESC LIMIT 10000");
        }
        else if(ui->comboBox->currentText()=="光照"){
            query.prepare("SELECT datetime, light FROM Times1 ORDER BY id DESC LIMIT 10000");
        }
    }
    if (!query.exec()) {
        std::cout << query.lastError().text().toStdString() << std::endl;
        return;
    }

    QVector<int> Paint_data;
    QVector<QString> datetimes;
    while (query.next()) {
        QString datetime = query.value(0).toString();
        int data_show = query.value(1).toInt();
        datetimes.prepend(datetime);        // 将时间添加到向量的开始，保证顺序
        Paint_data.prepend(data_show); // 将温度添加到向量的开始，保证顺序
    }
    Paint_cansu_now_Proc(datetimes,Paint_data);  // 调用之前实现的函数来绘制这些数据

    db.close();
}

void chart::Paint_cansu_now_Proc(const QVector<QString> &datetimes, const QVector<int> &Paint_data)
{
    QChart *chart = new QChart();
    QLineSeries *series = new QLineSeries();
    qDebug()<<Paint_data.size();

    QDateTime minDatetime = QDateTime::fromString(datetimes[datetimes.size()-100], "yyyy-MM-dd HH:mm:ss");
    QDateTime maxDatetime = QDateTime::fromString(datetimes[datetimes.size()-1], "yyyy-MM-dd HH:mm:ss");
    int span = minDatetime.secsTo(maxDatetime); // 计算时间跨度，单位为秒


    // 添加数据点到系列
    for (int i = Paint_data.size()-100; i < Paint_data.size(); ++i) {
        QDateTime datetime = QDateTime::fromString(datetimes[i], "yyyy-MM-dd HH:mm:ss");
        series->append(datetime.toMSecsSinceEpoch(), Paint_data[i]);
    }

    chart->addSeries(series);
    chart->legend()->hide();

    // 创建并设置X轴为时间轴


    QDateTimeAxis *axisX = new QDateTimeAxis;
    if (span > 2 * 24 * 3600) { // 超过两天
        axisX->setFormat("MM-dd"); // 设置刻度为天
    } else if (span > 2 * 3600) { // 超过两小时
        axisX->setFormat("MM-dd HH"); // 设置刻度为小时
    } else if (span > 2 * 60) { // 超过两分钟
        axisX->setFormat("HH:mm"); // 设置刻度为分钟
    } else {
        axisX->setFormat("HH:mm:ss"); // 设置刻度为秒
    }
    axisX->setTitleText("时间");
    axisX->setLabelsAngle(-75);
    QFont font;
    font.setPointSize(10);
    axisX->setLabelsFont(font);
    int tickCount ;
    if(Paint_data.size()<=10)   {
        tickCount=5;
    }
    else  if(Paint_data.size()>10&&Paint_data.size()<=100){
        tickCount=7;
    }

    axisX->setTickCount(tickCount);
    chart->setAxisX(axisX, series);

    // 创建并设置Y轴（假设Y轴数据为整数）
    QValueAxis *axisY = new QValueAxis();
    axisY->setLabelFormat("%i");
    if(ui->comboBox->currentText()=="温度"){
        axisY->setTitleText("温度 (°C)");
        chart->setTitle("历史温度数据");
    }
    else if(ui->comboBox->currentText()=="气体"){
        axisY->setTitleText("气体 (ppm)");
        chart->setTitle("历史气体数据");
    }
    else if(ui->comboBox->currentText()=="火焰"){
        axisY->setTitleText("火焰 (%)");
        chart->setTitle("历史火焰数据");
    }
    else if(ui->comboBox->currentText()=="震动"){
        axisY->setTitleText("震动 (µg/m³)");
        chart->setTitle("历史震动数据");
    }
    else if(ui->comboBox->currentText()=="光照"){
        axisY->setTitleText("光照 (lx)");
        chart->setTitle("历史光照数据");
    }

    axisY->applyNiceNumbers();
    chart->setAxisY(axisY, series);

    // 设置图表主题
    chart->setTheme(QChart::ChartThemeBlueCerulean);

    // 将图表设置到视图
    ui->graphicsView->setChart(chart);
    ui->graphicsView->setRenderHint(QPainter::Antialiasing); // 设置抗锯齿，以改善图形的视觉质量
}




void chart::on_pushButton_2_clicked()
{
    Paint_now_past_Flag=0;
    ui->pushButton_3->setText("OFF");
    if (QSqlDatabase::contains("qt_sql_default_connection")) {
        QSqlDatabase::removeDatabase("qt_sql_default_connection");
    }

    // 添加新的数据库连接
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "qt_sql_default_connection");
    db.setDatabaseName("lyshark.db");
    if (!db.open()) {
        std::cout << db.lastError().text().toStdString() << std::endl;
        return;
    }

    // 执行查询获取最新的10000个数据
    QSqlQuery query(db);
    if(ui->comboBox_2->currentText()=="节点一"){
        if(ui->comboBox->currentText()=="温度"){
            query.prepare("SELECT datetime, temprature FROM Times1 ORDER BY id DESC LIMIT 10000");
        }
        else if(ui->comboBox->currentText()=="气体"){
            query.prepare("SELECT datetime, comgas FROM Times1 ORDER BY id DESC LIMIT 10000");
        }
        else if(ui->comboBox->currentText()=="火焰"){
            query.prepare("SELECT datetime, flame FROM Times1 ORDER BY id DESC LIMIT 10000");
        }
        else if(ui->comboBox->currentText()=="震动"){
            query.prepare("SELECT datetime, shake FROM Times1 ORDER BY id DESC LIMIT 10000");
        }
        else if(ui->comboBox->currentText()=="光照"){
            query.prepare("SELECT datetime, light FROM Times1 ORDER BY id DESC LIMIT 10000");
        }
    }

    else if(ui->comboBox_2->currentText()=="节点二"){
        if(ui->comboBox->currentText()=="温度"){
            query.prepare("SELECT datetime, temprature FROM Times2 ORDER BY id DESC LIMIT 10000");
        }
        else if(ui->comboBox->currentText()=="气体"){
            query.prepare("SELECT datetime, comgas FROM Times2 ORDER BY id DESC LIMIT 10000");
        }
        else if(ui->comboBox->currentText()=="火焰"){
            query.prepare("SELECT datetime, flame FROM Times2 ORDER BY id DESC LIMIT 10000");
        }
        else if(ui->comboBox->currentText()=="震动"){
            query.prepare("SELECT datetime, shake FROM Times2 ORDER BY id DESC LIMIT 10000");
        }
        else if(ui->comboBox->currentText()=="光照"){
            query.prepare("SELECT datetime, light FROM Times1 ORDER BY id DESC LIMIT 10000");
        }
    }

    else if(ui->comboBox_2->currentText()=="节点三"){
        if(ui->comboBox->currentText()=="温度"){
            query.prepare("SELECT datetime, temprature FROM Times3 ORDER BY id DESC LIMIT 10000");
        }
        else if(ui->comboBox->currentText()=="气体"){
            query.prepare("SELECT datetime, comgas FROM Times3 ORDER BY id DESC LIMIT 10000");
        }
        else if(ui->comboBox->currentText()=="火焰"){
            query.prepare("SELECT datetime, flame FROM Times3 ORDER BY id DESC LIMIT 10000");
        }
        else if(ui->comboBox->currentText()=="震动"){
            query.prepare("SELECT datetime, shake FROM Times3 ORDER BY id DESC LIMIT 10000");
        }
        else if(ui->comboBox->currentText()=="光照"){
            query.prepare("SELECT datetime, light FROM Times1 ORDER BY id DESC LIMIT 10000");
        }
    }

    if (!query.exec()) {
        std::cout << query.lastError().text().toStdString() << std::endl;
        return;
    }

    QVector<int> temperature_data;
    QVector<QString> datetimes;
    while (query.next()) {
        QString datetime = query.value(0).toString();
        int temperature = query.value(1).toInt();
        datetimes.prepend(datetime);        // 将时间添加到向量的开始，保证顺序
        temperature_data.prepend(temperature); // 将温度添加到向量的开始，保证顺序
    }
    Paint_cansu_past_Proc(datetimes,temperature_data);  // 调用之前实现的函数来绘制这些数据
    db.close();
}

void chart::Paint_cansu_past_Proc(const QVector<QString>& datetimes, const QVector<int>& temperatures)
{
    QDateTime start_timet = ui->dateTime_start->dateTime();
    QDateTime end_timet = ui->dateTime_end->dateTime();

    QString start_user_time = start_timet.toString("yyyy-MM-dd HH:mm:ss");
    QString end_user_time = end_timet.toString("yyyy-MM-dd HH:mm:ss");
    start_timet = QDateTime::fromString(start_user_time, "yyyy-MM-dd hh:mm:ss");
    end_timet = QDateTime::fromString(end_user_time, "yyyy-MM-dd hh:mm:ss");
    int flag=0;
    if(start_user_time!=""&&end_user_time!=""&&start_timet<end_timet)
        flag=1;
    if(flag){
        qDebug()<<start_user_time;
        qDebug()<<end_user_time;
        QChart *chart = new QChart();
        QLineSeries *series = new QLineSeries();
        qDebug()<<temperatures.size();

        QDateTime start_timet1 = QDateTime::fromString("2999-12-30 23:59:59", "yyyy-MM-dd hh:mm:ss");
        QDateTime end_timet1 = QDateTime::fromString("2000-1-1 1:1:0", "yyyy-MM-dd hh:mm:ss");

        for (int i = 0; i < temperatures.size(); ++i) {
            if(datetimes[i].toStdString() >= start_user_time.toStdString() && datetimes[i].toStdString() <= end_user_time.toStdString()){
                QDateTime datetime = QDateTime::fromString(datetimes[i], "yyyy-MM-dd HH:mm:ss");
                series->append(datetime.toMSecsSinceEpoch(), temperatures[i]);
                if(start_timet1>datetime){
                    start_timet1=datetime;
                }
                if(end_timet1<datetime){
                    end_timet1=datetime;
                }
            }
        }
        int span = start_timet1.secsTo(end_timet1); // 计算时间跨度，单位为秒
        chart->addSeries(series);
        chart->legend()->hide();
        // 创建并设置X轴为时间轴


        QDateTimeAxis *axisX = new QDateTimeAxis;
        if (span > 2 * 24 * 3600) { // 超过两天
            axisX->setFormat("MM-dd"); // 设置刻度为天
        } else if (span > 2 * 3600) { // 超过两小时
            axisX->setFormat("MM-dd HH"); // 设置刻度为小时
        } else if (span > 2 * 60) { // 超过两分钟
            axisX->setFormat("HH:mm"); // 设置刻度为分钟
        } else {
            axisX->setFormat("HH:mm:ss"); // 设置刻度为秒
        }
        axisX->setTitleText("时间");
        axisX->setLabelsAngle(-75);
        QFont font;
        font.setPointSize(10);
        axisX->setLabelsFont(font);
        int tickCount ;
        if(span<=2 * 60)   {
            tickCount=5;
        }
        else  if(span>=2 * 60){
            tickCount=7;
        }

        axisX->setTickCount(tickCount);
        chart->setAxisX(axisX, series);

        // 创建并设置Y轴（假设Y轴数据为整数）
        QValueAxis *axisY = new QValueAxis();
        axisY->setLabelFormat("%i");
        if(ui->comboBox->currentText()=="温度"){
            axisY->setTitleText("温度 (°C)");
            chart->setTitle("历史温度数据");
        }
        else if(ui->comboBox->currentText()=="气体"){
            axisY->setTitleText("气体 (ppm)");
            chart->setTitle("历史气体数据");
        }
        else if(ui->comboBox->currentText()=="火焰"){
            axisY->setTitleText("火焰 (%x)");
            chart->setTitle("历史火焰数据");
        }
        else if(ui->comboBox->currentText()=="震动"){
            axisY->setTitleText("震动 (µg/m³)");
            chart->setTitle("历史震动数据");
        }
        else if(ui->comboBox->currentText()=="光照"){
            axisY->setTitleText("光照 (lx)");
            chart->setTitle("历史光照数据");
        }

        axisY->applyNiceNumbers();
        chart->setAxisY(axisY, series);

        // 设置图表主题
        chart->setTheme(QChart::ChartThemeBlueCerulean);

        // 将图表设置到视图
        ui->graphicsView->setChart(chart);
        ui->graphicsView->setRenderHint(QPainter::Antialiasing); // 设置抗锯齿，以改善图形的视觉质量

    }
    else if(!flag){
        qDebug()<<start_user_time;
        qDebug()<<end_user_time;
        QChart *chart = new QChart();
        QLineSeries *series = new QLineSeries();
        qDebug()<<temperatures.size();

        QDateTime minDatetime = QDateTime::fromString(datetimes[0], "yyyy-MM-dd HH:mm:ss");
        QDateTime maxDatetime = QDateTime::fromString(datetimes[datetimes.size()-1], "yyyy-MM-dd HH:mm:ss");
        int span = minDatetime.secsTo(maxDatetime); // 计算时间跨度，单位为秒


        // 添加数据点到系列
//        for (int i = 0; i < temperatures.size(); ++i) {
//            QDateTime datetime = QDateTime::fromString(datetimes[i], "yyyy-MM-dd HH:mm:ss");
//            series->append(datetime.toMSecsSinceEpoch(), temperatures[i]);
//        }

        chart->addSeries(series);
        chart->legend()->hide();

        // 创建并设置X轴为时间轴


        QDateTimeAxis *axisX = new QDateTimeAxis;
        if (span > 2 * 24 * 3600) { // 超过两天
            axisX->setFormat("MM-dd"); // 设置刻度为天
        } else if (span > 2 * 3600) { // 超过两小时
            axisX->setFormat("MM-dd HH"); // 设置刻度为小时
        } else if (span > 2 * 60) { // 超过两分钟
            axisX->setFormat("HH:mm"); // 设置刻度为分钟
        } else {
            axisX->setFormat("HH:mm:ss"); // 设置刻度为秒
        }
        axisX->setTitleText("时间");
        axisX->setLabelsAngle(-75);
        QFont font;
        font.setPointSize(10);
        axisX->setLabelsFont(font);
        int tickCount ;
        if(temperatures.size()<=10)   {
            tickCount=5;
        }
        else  if(temperatures.size()>10&&temperatures.size()<=100){
            tickCount=7;
        }

//        axisX->setTickCount(tickCount);
//        chart->setAxisX(axisX, series);

        // 创建并设置Y轴（假设Y轴数据为整数）
        QValueAxis *axisY = new QValueAxis();
        axisY->setLabelFormat("%i");
        if(ui->comboBox->currentText()=="温度"){
            axisY->setTitleText("温度 (°C)");
            chart->setTitle("历史温度数据");
        }
        else if(ui->comboBox->currentText()=="气体"){
            axisY->setTitleText("气体 (ppm)");
            chart->setTitle("历史气体数据");
        }
        else if(ui->comboBox->currentText()=="火焰"){
            axisY->setTitleText("火焰 (lx)");
            chart->setTitle("历史火焰数据");
        }
        else if(ui->comboBox->currentText()=="震动"){
            axisY->setTitleText("震动 (µg/m³)");
            chart->setTitle("历史震动数据");
        }
        else if(ui->comboBox->currentText()=="光照"){
            axisY->setTitleText("光照 (lx)");
            chart->setTitle("历史光照数据");
        }
//        axisY->applyNiceNumbers();
//        chart->setAxisY(axisY, series);

        // 设置图表主题
        chart->setTheme(QChart::ChartThemeBlueCerulean);

        // 将图表设置到视图
        ui->graphicsView->setChart(chart);
        ui->graphicsView->setRenderHint(QPainter::Antialiasing); // 设置抗锯齿，以改善图形的视觉质量
    }

}
//实时数据监测开关
void chart::on_pushButton_3_clicked()
{
    if(Paint_now_past_Flag==1){
        ui->pushButton_3->setText("OFF");
        Paint_now_past_Flag=0;
    }
    else {
        ui->pushButton_3->setText("ON");
        Paint_now_past_Flag=1;
    }
}

void chart::back_set_color()
{
    ui->label_back->setStyleSheet(
        "QLabel {"
        "background: qlineargradient(x1:0, y1:0, x2:1, y2:1, "
        "stop:0 rgba(200,230,255,160), stop:1 rgba(170,220,255,200));"
        "border-radius: 8px;"
        "}"
    );


    ui->label_button->setStyleSheet(
        "QLabel {"
        "background: qlineargradient(x1:1, y1:0, x2:0, y2:1, "
        "stop:0 rgba(180,240,255,150), stop:1 rgba(130,200,250,200));"
        "border-radius: 8px;"
        "}"
    );

    ui->label_cha->setStyleSheet(
        "QLabel {"
        "background: qlineargradient(x1:0, y1:1, x2:1, y2:0, "
        "stop:0 rgba(190,220,235,130), stop:1 rgba(100,180,240,180));"
        "border-radius: 8px;"
        "}"
    );

    ui->label_time->setStyleSheet(
        "QLabel {"
        "background: qlineargradient(x1:0, y1:0, x2:1, y2:0, "
        "stop:0 rgba(160,220,255,100), stop:1 rgba(220,240,255,160));"
        "border-radius: 8px;"
        "}"
    );
}



void chart::on_back_button_clicked()
{
    emit this->back();
}


chart::~chart()
{
    delete ui;
}








